package com.mujin.keji.collectionsystem.module.updata.views;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.base.BaseVo;
import com.mujin.keji.collectionsystem.common.EmailSituationEnum;
import com.mujin.keji.collectionsystem.common.ErrorEnum;
import com.mujin.keji.collectionsystem.common.HouseApplianceEnum;
import com.mujin.keji.collectionsystem.common.InnerDecorationEnum;
import com.mujin.keji.collectionsystem.common.LivingSituationEnum;
import com.mujin.keji.collectionsystem.common.RepayPowerEnum;
import com.mujin.keji.collectionsystem.common.SyncDataMethod;
import com.mujin.keji.collectionsystem.common.VisitHouseEnum;
import com.mujin.keji.collectionsystem.common.VisitStatusEnum;
import com.mujin.keji.collectionsystem.db.dao.VisitDao;
import com.mujin.keji.collectionsystem.db.database.AppDataBase;
import com.mujin.keji.collectionsystem.db.domain.SaveVisitRecordBean;
import com.mujin.keji.collectionsystem.db.domain.VisitApplyBean;
import com.mujin.keji.collectionsystem.db.domain.VisitCountBean;
import com.mujin.keji.collectionsystem.dto.UploadFileDto;
import com.mujin.keji.collectionsystem.exception.ApiException;
import com.mujin.keji.collectionsystem.exception.ExceptionEngine;
import com.mujin.keji.collectionsystem.exception.ServerException;
import com.mujin.keji.collectionsystem.http.Api;
import com.mujin.keji.collectionsystem.http.HttpUtils;
import com.mujin.keji.collectionsystem.listeners.ClickFileListener;
import com.mujin.keji.collectionsystem.module.login.dto.LoginDto;
import com.mujin.keji.collectionsystem.module.login.dto.UserDto;
import com.mujin.keji.collectionsystem.module.login.repository.LoginRepository;
import com.mujin.keji.collectionsystem.module.login.vo.LoginCollectionVo;
import com.mujin.keji.collectionsystem.module.main.views.MainActivity;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.RefreshVo;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.SaveVisitRecordReq;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.SearchVo;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.UploadWithBase64Request;
import com.mujin.keji.collectionsystem.module.outboundtask.vo.VisitFileVo;
import com.mujin.keji.collectionsystem.module.updata.adapter.UpFileListAdapter;
import com.mujin.keji.collectionsystem.module.updata.dto.ShowVisitUserDto;
import com.mujin.keji.collectionsystem.module.updata.dto.VisitUserDto;
import com.mujin.keji.collectionsystem.module.updata.vo.UpLoadFileVo;
import com.mujin.keji.collectionsystem.module.updata.vo.UploadVo;
import com.mujin.keji.collectionsystem.net.NetworkUtil;
import com.mujin.keji.collectionsystem.permissions.PermissionsObserver;
import com.mujin.keji.collectionsystem.utils.AssambleReqUtil;
import com.mujin.keji.collectionsystem.utils.DialogUtils;
import com.mujin.keji.collectionsystem.utils.DisplayUtil;
import com.mujin.keji.collectionsystem.utils.Dom4jUtil;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.FileUtil;
import com.mujin.keji.collectionsystem.utils.IpUtils;
import com.mujin.keji.collectionsystem.utils.SPUtil;
import com.mujin.keji.collectionsystem.utils.ToastUtils;
import com.mujin.keji.collectionsystem.utils.ZipUtils;
import com.mujin.keji.collectionsystem.widget.CustomerItemDecoration;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Response;

/**
 * 某个案件的文件列表
 *
 * @author weishixiong
 * @Time 2018-05-8
 */


public class UploadSingleUserActivity extends BaseActivity implements View.OnClickListener, ClickFileListener {
    private static final String LOGGER = "上传文件";

    private Button btnRecord;
    private Button btnPhoto;
    private ImageView ivLeftText;
    private View vBack;
    private TextView tvProgress;
    private ProgressBar progressBar;
    private TextView tvSpeed;
    private TextView tvVisitText;
    private TextView tvVisitCount;
    private TextView tvFileCount;
    private SwipeMenuRecyclerView rvRecord;
    private SwipeMenuRecyclerView rvPhoto;
    private LinearLayout btnOk;
    private List<VisitUserDto> recordList;
    private List<VisitUserDto> photoList;
    private List<VisitUserDto> visitUserDtoList;
    private LinearLayoutManager lm_record;
    private LinearLayoutManager lm_photo;
    private UpFileListAdapter recordAdapter;
    private UpFileListAdapter photoAdapter;
    private SwipeMenuItemClickListener listener_photo;
    private SwipeMenuItemClickListener listener_record;
    private SwipeMenuCreator sm_photo;
    private SwipeMenuCreator sm_record;
    private List<UpLoadFileVo> upLoadFileVoList;//封装多次上传参数
    private ShowVisitUserDto showVisitUserDto;
    private UpLoadFileVo upLoadFileVo;
    private LinearLayout llHaveData;
    private LinearLayout llNoData;
    private TextView tvNoData;
    private TextView tvFileText;
    private int type;//0 录音 1 照片
    private LinearLayout llUpload;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        CcsApplication.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        CcsApplication.removeActivity(this);
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        setResult(1001);
    }

    @Override
    protected void createViewModel() {
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void initFileList(ShowVisitUserDto showVisitUserDto) {
        this.showVisitUserDto = showVisitUserDto;
        /**
         * 初始化多次上传的数据参数
         * upLoadFileVoList
         */
        initUploadData();
        /**
         * 初始化进度条
         */
        initProgress();
        /**
         * 初始化照片和录音的数据
         */
        initVisitUserDtoList();
        /**
         * 刷新列表视图
         */
        ruslushListView();

    }

    /**
     * 初始化照片和录音的总数据
     */
    private void initVisitUserDtoList() {
        visitUserDtoList = new ArrayList<>();
        for (int i = 0; i < showVisitUserDto.getVisitUserDtoList().size(); i++) {
            visitUserDtoList.add(showVisitUserDto.getVisitUserDtoList().get(i));
        }
        filterUserFile();

    }

    /**
     * 过滤掉非当前用户的文件
     */
    private void filterUserFile() {
        if (!EmptyUtils.isNotEmpty(visitUserDtoList)) {
            return;
        }
        LoginDto dto = SPUtil.getData(Constant.SP.SP, Constant.SP.LOGIN_KEY, LoginDto.class, null);
        String userCount = dto.getUserAccount();
        if (TextUtils.isEmpty(userCount)) {
            return;
        }
        for (int i = 0; i < visitUserDtoList.size(); i++) {
            if (!(userCount.equals(visitUserDtoList.get(i).getUserAccount()))) {
                visitUserDtoList.remove(i);
                filterUserFile();
            }
        }
    }

    /**
     * 初始化列表ui
     */
    private void ruslushListView() {
        if (EmptyUtils.isNotEmpty(visitUserDtoList)) {
            llHaveData.setVisibility(View.VISIBLE);
            llNoData.setVisibility(View.GONE);
            /**
             * 初始化需要展示列表的数据
             */
            initListViewData();

            /**
             * 展示列表视图
             */
            showListViewUi();
            /**
             * 展示文件数量
             */


        } else {
            llHaveData.setVisibility(View.GONE);
            llNoData.setVisibility(View.VISIBLE);
            tvVisitCount.setText("0");
            tvFileCount.setText("0");
            tvNoData.setText("没有待上传文件");
        }

    }

    /**
     * 展示列表视图
     */
    private void showListViewUi() {
        recordAdapter = new UpFileListAdapter(this, recordList, this);
        photoAdapter = new UpFileListAdapter(this, photoList, this);
        rvRecord.setAdapter(recordAdapter);
        rvPhoto.setAdapter(photoAdapter);
        if (EmptyUtils.isNotEmpty(visitUserDtoList)) {
            tvVisitCount.setText("1");
            tvFileCount.setText(visitUserDtoList.size() + "");
            if (type == 0) {
                tvFileCount.setText(recordList.size() + "");
            } else {
                tvFileCount.setText(photoList.size() + "");
            }
        } else {
            tvVisitCount.setText("0");
            tvFileCount.setText("0");
        }
        /**
         * 如果是点的照片 那就显示照片的列表
         */
        if (getIntent().getIntExtra("type", 0) == 1) {
            showPhotoView();
        }
    }

    /**
     * 拆分录音和照片的数据
     */
    private void initListViewData() {
        recordList = new ArrayList<>();
        photoList = new ArrayList<>();
        for (int i = 0; i < visitUserDtoList.size(); i++) {
            if ("1".equals(visitUserDtoList.get(i).getFileType())) {
                recordList.add(visitUserDtoList.get(i));
            } else if ("2".equals(visitUserDtoList.get(i).getFileType())) {
                photoList.add(visitUserDtoList.get(i));
            }
        }
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_uploadfilelist;
    }

    private boolean tip;//是否提示过

    @Override
    public void initView() {
        setleftImage(R.drawable.image_arrow_left_white, true, null);
        btnRecord = (Button) findViewById(R.id.btn_record);
        btnPhoto = (Button) findViewById(R.id.btn_photo);
        ivLeftText = (ImageView) findViewById(R.id.iv_left_text);
        vBack = (View) findViewById(R.id.v_back);
        tvProgress = (TextView) findViewById(R.id.tv_progress);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        tvSpeed = (TextView) findViewById(R.id.tv_speed);
        tvVisitText = (TextView) findViewById(R.id.tv_visit_text);
        tvVisitCount = (TextView) findViewById(R.id.tv_visit_count);
        tvFileCount = (TextView) findViewById(R.id.tv_file_count);
        rvRecord = (SwipeMenuRecyclerView) findViewById(R.id.rv_record);
        rvPhoto = (SwipeMenuRecyclerView) findViewById(R.id.rv_photo);
        btnOk = (LinearLayout) findViewById(R.id.btn_ok);
        llHaveData = (LinearLayout) findViewById(R.id.ll_have_data);
        tvNoData = (TextView) findViewById(R.id.tv_no_data);
        llNoData = (LinearLayout) findViewById(R.id.ll_no_data);
        tvFileText = (TextView) findViewById(R.id.tv_file_text);
        llUpload = (LinearLayout) findViewById(R.id.ll_upload);

        /**
         * RecyclerView的Item的Menu点击监听。
         */
        listener_photo = new SwipeMenuItemClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge) {
                menuBridge.closeMenu();

                int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
                final int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
                //   int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

                if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
//                    List<VisitUserDto> visitUserDtos = new ArrayList<>();
//                    visitUserDtos.add(photoList.get(adapterPosition));
//                    deletedFile(visitUserDtos);
//                    photoList.remove(adapterPosition);
//                    photoAdapter.notifyDataSetChanged();
//                    tvFileCount.setText(String.valueOf(photoList.size()));
                }
            }


        };
        listener_record = new SwipeMenuItemClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge) {
                menuBridge.closeMenu();
                int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
                final int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
                //   int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。
                if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
//                    List<VisitUserDto> visitUserDtos = new ArrayList<>();
//                    visitUserDtos.add(recordList.get(adapterPosition));
//                    deletedFile(visitUserDtos);
//                    recordList.remove(adapterPosition);
//                    recordAdapter.notifyDataSetChanged();
//                    tvFileCount.setText(String.valueOf(recordList.size()));
                }
            }
        };
        // 创建菜单：
        sm_photo = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int viewType) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(UploadSingleUserActivity.this)
                        .setImage(R.drawable.image_delete)// 各种文字和图标属性设置。
                        .setText("删除")
                        .setTextSize(DisplayUtil.sp2px(UploadSingleUserActivity.this, 5))
                        .setTextColor(getResources().getColor(R.color.color_white))
                        .setWidth(DisplayUtil.dip2px(UploadSingleUserActivity.this, 100))
                        .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
                        .setBackgroundColor(Color.parseColor("#FF0000"));
                rightMenu.addMenuItem(deleteItem); // 在Item左侧添加一个菜单。
            }
        };
        sm_record = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int viewType) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(UploadSingleUserActivity.this)
                        .setImage(R.drawable.image_delete)// 各种文字和图标属性设置。
                        .setText("删除")
                        .setTextSize(DisplayUtil.sp2px(UploadSingleUserActivity.this, 5))
                        .setTextColor(getResources().getColor(R.color.color_white))
                        .setWidth(DisplayUtil.dip2px(UploadSingleUserActivity.this, 100))
                        .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
                        .setBackgroundColor(Color.parseColor("#FF0000"));
                rightMenu.addMenuItem(deleteItem); // 在Item左侧添加一个菜单。
            }
        };

        lm_record = new LinearLayoutManager(this);
        lm_photo = new LinearLayoutManager(this);
        rvRecord.setLayoutManager(lm_record);
        rvPhoto.setLayoutManager(lm_photo);
        //添加装饰类
        rvRecord.addItemDecoration(new CustomerItemDecoration(DisplayUtil.dip2px(this, 10)));
        rvPhoto.addItemDecoration(new CustomerItemDecoration(DisplayUtil.dip2px(this, 10)));
        //待外访的案件可以滑动删除
        if (getIntent().getIntExtra("status", 2) == 1) {
//            //滑动删除需要配置
//            rvRecord.setSwipeMenuCreator(sm_record);
//            rvRecord.setSwipeMenuItemClickListener(listener_record);
//            rvPhoto.setSwipeMenuCreator(sm_photo);
//            rvPhoto.setSwipeMenuItemClickListener(listener_photo);
//
//            llUpload.setVisibility(View.GONE);
//            //重新这是view的magrin
//            RelativeLayout.LayoutParams lp_record = new RelativeLayout.LayoutParams(rvRecord.getLayoutParams());
//            lp_record.setMargins(0, DisplayUtil.dip2px(this, 10), 0, 0);
//            rvRecord.setLayoutParams(lp_record);
//
//            RelativeLayout.LayoutParams lp_photo = new RelativeLayout.LayoutParams(rvPhoto.getLayoutParams());
//            lp_photo.setMargins(0, DisplayUtil.dip2px(this, 10), 0, 0);
//            rvPhoto.setLayoutParams(lp_photo);

        } else {
            llUpload.setVisibility(View.VISIBLE);
        }


    }


    /**
     * 初始化多次上传的数据参数
     * upLoadFileVoList
     */
    private void initUploadData() {
        upLoadFileVoList = new ArrayList<>();
        UploadVo vo = new UploadVo();
        vo.setVisitApplyId(showVisitUserDto.getVisitApplyId());
        vo.setRecordTime(showVisitUserDto.getVisitUserDtoList().get(0).getFileTime());
        vo.setVisitorAddress(showVisitUserDto.getVisitUserDtoList().get(0).getFileAdress());
        for (int j = 0; j < showVisitUserDto.getVisitUserDtoList().size(); j++) {
            List<File> uploadFiles = new ArrayList<>();
            uploadFiles.add(showVisitUserDto.getVisitUserDtoList().get(j).getFile());
            upLoadFileVo = new UpLoadFileVo();
            upLoadFileVo.setVo(vo);
            upLoadFileVo.setUploadFiles(uploadFiles);
            upLoadFileVoList.add(upLoadFileVo);

        }

    }

    @Override
    public void initData() {
        appDataBase = AppDataBase.getInstance(UploadSingleUserActivity.this);
    }


    @Override
    public void initListener() {
        btnOk.setOnClickListener(this);
        btnRecord.setOnClickListener(this);
        btnPhoto.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_ok:
                if (!NetworkUtil.isNetworkAvailable(this)) {
                    ToastUtils.showToast("请开启手机网络");
                    return;
                }
                upload();
                break;
            case R.id.btn_photo:
                showPhotoView();
                break;
            case R.id.btn_record:
                showRecordView();
                break;
        }
    }

    /**
     * 展示录音列表
     */
    private void showRecordView() {
        btnPhoto.setBackgroundResource(R.drawable.shape_file_normal_bg);
        btnRecord.setBackgroundResource(R.drawable.shape_file_select_bg);
        btnPhoto.setTextColor(getResources().getColor(R.color.color_white));
        btnRecord.setTextColor(getResources().getColor(R.color.color_main_title));
        rvPhoto.setVisibility(View.GONE);
        rvRecord.setVisibility(View.VISIBLE);
        tvFileText.setText("录音文件:");
        tvFileCount.setText(recordList.size() + "");
        type = 0;
    }

    /**
     * 展示照片列表
     */
    private void showPhotoView() {
        btnPhoto.setBackgroundResource(R.drawable.shape_file_select_bg);
        btnRecord.setBackgroundResource(R.drawable.shape_file_normal_bg);
        btnPhoto.setTextColor(getResources().getColor(R.color.color_main_title));
        btnRecord.setTextColor(getResources().getColor(R.color.color_white));
        rvPhoto.setVisibility(View.VISIBLE);
        rvRecord.setVisibility(View.GONE);
        tvFileText.setText("照片文件:");
        tvFileCount.setText(photoList.size() + "");
        type = 1;
    }


    //总的大小
    private int allSize;

    private int successSize;//上传成功的数量

    /**
     * 初始化进度条
     */

    private void initProgress() {
        allSize = showVisitUserDto.getVisitUserDtoList().size();
        progressBar.setMax(allSize);
        //
        tvProgress.setText("0/" + allSize);

    }


    private AppDataBase appDataBase;

    /**
     * 实现上传
     */
    private void upload() {
        btnOk.setEnabled(false);
        btnOk.setBackgroundResource(R.drawable.shape_button_select_dark_bg);
        //上传文件
        getLoadingDialog().showDialog();
        //查询用户信息
        String userName = SPUtil.getData(Constant.SP.SP, Constant.SP.USER, String.class, null);
        Flowable<List<UserDto>> flowable = appDataBase.getUserDao().findUserList(userName);
        flowable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<UserDto>>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(100);
                        Log.e(TAG, "Subscription: " + s);
                    }

                    @Override
                    public void onNext(List<UserDto> userDtos) {
                        if (!EmptyUtils.isNotEmpty(userDtos)) {
                            ToastUtils.showToast("获取用户信息失败");
                            getLoadingDialog().dismiss();
                            btnOk.setEnabled(true);
                            btnOk.setBackgroundResource(R.drawable.shape_button_select_bg);
                            return;
                        }
                        Log.e(TAG, "onNext: " + userDtos.toString());
                        UserDto userDto = userDtos.get(0);
                        //获取用户session
                        initLoginSession(userDto);


                    }

                    @Override
                    public void onError(Throwable t) {
                        getLoadingDialog().dismiss();
                        Log.e(TAG, "onError: " + t);
                        getLoadingDialog().dismiss();
                        ApiException exception = ExceptionEngine.handleException(t);
                        ToastUtils.showToast(exception.getCode() + "-" + exception.getMsg());
                        btnOk.setEnabled(true);
                        btnOk.setBackgroundResource(R.drawable.shape_button_select_bg);


                    }

                    @Override
                    public void onComplete() {
                        Log.e(TAG, "onComplete: ");
                    }
                });


    }

    /**
     * 准备上传
     *
     * @param session
     */
    private void initToUpload(String session) {
        if (successSize >= allSize) {
            return;
        }
        /**
         *  外访参数
         */
        UploadVo vo = upLoadFileVoList.get(0).getVo();


        List<VisitFileVo> visitFileVoList = new ArrayList();
        if (!EmptyUtils.isNotEmpty(upLoadFileVoList.get(successSize).getUploadFiles())) {
            return;
        }
        //文件
        File file = upLoadFileVoList.get(successSize).getUploadFiles().get(0);
        //上传
        VisitFileVo visitFileVo = new VisitFileVo();
        List<UploadWithBase64Request> requests = new ArrayList<>();
        UploadWithBase64Request uploadWithBase64Request = new UploadWithBase64Request();
        visitFileVo.setVisitApplyId(Long.valueOf(vo.getVisitApplyId()));
        //
        uploadWithBase64Request.setFileName(file.getName());

        String content = IpUtils.fileToBase64String(file);
        if (content == null) {
            Log.e(TAG, "initToUpload: content为空，执行下一个");
            return;
        }
        uploadWithBase64Request.setContent(content);

        uploadWithBase64Request.setFileNameExt(file.getName().split("\\.")[1]);
        requests.add(uploadWithBase64Request);
        visitFileVo.setVisitApplyId(Long.valueOf(vo.getVisitApplyId()));
        visitFileVo.setUploadWithBase64RequestList(requests);
        visitFileVoList.add(visitFileVo);

        Log.e(TAG, "上传第 " + successSize + "个文件");
        //上传文件
        uploadFile(visitFileVoList, session, vo.getVisitApplyId(), file);


    }

    private String session;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 200) {
                //刷新列视图
                getLoadingDialog().dismiss();
                //刷新列视图
                ToastUtils.showToast("已更新完成");
                llHaveData.setVisibility(View.GONE);
                llNoData.setVisibility(View.VISIBLE);
                tvVisitCount.setText("0");
                tvFileCount.setText("0");
                tvNoData.setText("没有待上传文件");
            }
            /**
             * 拿到session 完之后 去上传
             */
            else if (msg.what == 2001) {
                session = (String) msg.obj;
                initToUpload(session);
                RefreshVo vo = new RefreshVo(200);
                EventBus.getDefault().post(vo);
            } else if (msg.what == 300) {
                //刷新列视图
                getLoadingDialog().dismiss();
                //刷新列视图
                ToastUtils.showToast("客户端异常");

            } else {
                //刷新列视图
                getLoadingDialog().dismiss();
                ToastUtils.showToast((String) msg.obj);
                btnOk.setEnabled(true);
                btnOk.setBackgroundResource(R.drawable.shape_button_select_bg);
            }
        }
    };

    /**
     * 上传记录
     *
     * @param applyId
     */
    public void uploadVisitRecord(Long applyId, String session) {


        //上传外访记录
        Flowable<SaveVisitRecordBean> flowableQuery = appDataBase.getVisitDao().queryAllVisitRecord(applyId);
        flowableQuery.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<SaveVisitRecordBean>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(100);
                        Log.e(TAG, "Subscription: " + s);
                    }

                    @Override
                    public void onNext(SaveVisitRecordBean saveVisitRecordBean) {


                        String json = JSONObject.toJSONString(saveVisitRecordBean);

                        SaveVisitRecordReq saveVisitRecordReq = JSONObject.parseObject(json, SaveVisitRecordReq.class);

                        if (null != saveVisitRecordBean.getIsKown()) {
                            saveVisitRecordReq.setIsKown(saveVisitRecordBean.getIsKown() == 0 ? "no" : "yes");
                        }
                        saveVisitRecordReq.setEmailSituation(saveVisitRecordBean.getEmailSituation());
                        //saveVisitRecordReq.setBeginTime(saveVisitRecordBean.getBeginTime());
//            saveVisitRecordReq.setBeginTime(saveVisitRecordBean.getBeginTime());
                        //外访开始时间
                        saveVisitRecordReq.setBeginTime(saveVisitRecordBean.getVisitTimeStr());
                        //外访结速地址
                        saveVisitRecordReq.setVisitAddress(saveVisitRecordBean.getVisitEndAddress());

                        saveVisitRecordReq.setHouseAppliance(HouseApplianceEnum.find(saveVisitRecordBean.getHouseAppliance()));

                        saveVisitRecordReq.setInnerDecoration(InnerDecorationEnum.find(saveVisitRecordBean.getInnerDecoration()));
                        saveVisitRecordReq.setLivingSituation(LivingSituationEnum.find(saveVisitRecordBean.getLivingSituation()));
                        saveVisitRecordReq.setRepayPower(RepayPowerEnum.find(saveVisitRecordBean.getRepayPower()));
                        saveVisitRecordReq.setVisitHouse(VisitHouseEnum.find(saveVisitRecordBean.getVisitHouse()));

                        saveVisitRecordReq.setVisitMark(saveVisitRecordBean.getCaseDevelopment());
                        saveVisitRecordReq.setVisitCode(saveVisitRecordBean.getTaskCode());

                        BaseVo baseVo = AssambleReqUtil.assambleReqMap(SyncDataMethod.saveRecord, session, saveVisitRecordReq);

                        //查询用户信息
                        Flowable<JSONObject> flowable = Api.updateApplyStatus(baseVo);
                        flowable.subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Subscriber<JSONObject>() {
                                    @Override
                                    public void onSubscribe(Subscription s) {
                                        s.request(100);
                                    }

                                    @Override
                                    public void onNext(JSONObject result) {
                                        recordList.clear();
                                        photoList.clear();
                                        recordAdapter.notifyDataSetChanged();
                                        photoAdapter.notifyDataSetChanged();
                                        getLoadingDialog().dismiss();
                                        Log.e(TAG, "onNext: " + result);
                                        getLoadingDialog().dismiss();
                                        if (EmptyUtils.isNotEmpty(result)) {
                                            finishApplay(applyId);
                                        } else {
                                            ToastUtils.showToast("保存外访记录失败");
                                        }

                                    }

                                    @Override
                                    public void onError(Throwable t) {
                                        getLoadingDialog().dismiss();
                                        ApiException exception = ExceptionEngine.handleException(t);
                                        ToastUtils.showToast(exception.getCode() + "-" + exception.getMsg());

                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });


                    }

                    @Override
                    public void onError(Throwable t) {
                        getLoadingDialog().dismiss();
                        Log.e(TAG, "onError: " + t);
                        getLoadingDialog().dismiss();
                        ApiException exception = ExceptionEngine.handleException(t);
                        ToastUtils.showToast(exception.getCode() + "-" + exception.getMsg());


                    }

                    @Override
                    public void onComplete() {
                        Log.e(TAG, "onComplete: ");
                    }
                });


    }

    /**
     * 完成外访
     *
     * @param
     */
    private void finishApplay(Long applyId) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    VisitDao visitDao = appDataBase.getVisitDao();
                    VisitApplyBean visitApplyBean = visitDao.queryVisitList(applyId);
                    visitApplyBean.setStatus(VisitStatusEnum.VISIT_WANCHENG.getCode());
                    visitDao.updateVisitApply(visitApplyBean);
                    //更新条数
                    VisitCountBean visitCountBean = visitDao.findVisitCountDetail();
                    visitCountBean.setVisited((visitCountBean.getVisited() == null ? 0 : visitCountBean.getVisited()) - 1);
                    visitCountBean.setFinish((visitCountBean.getFinish() == null ? 0 : visitCountBean.getFinish()) + 1);
                    visitDao.updateVisitCount(visitCountBean);
                } catch (Exception e) {
                    handler.sendEmptyMessage(300);
                    return;
                }

                handler.sendEmptyMessage(200);
            }
        }.start();


    }


    /**
     * 上传文件
     *
     * @param visitFileVoList
     * @param session
     * @return
     */
    private void uploadFile(List<VisitFileVo> visitFileVoList, String session, String applyId, File file) {

        BaseVo baseVo = AssambleReqUtil.assambleReqMap(SyncDataMethod.visitUpload, session, visitFileVoList);
        Log.e(TAG, "uploadFile: " + baseVo.toString());
        Log.e(TAG, "uploadFile: 正在上传文件....");
        Flowable<UploadFileDto> flowable = Api.uploadSingle(baseVo);
        flowable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<UploadFileDto>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(100);
                        Log.e(TAG, "onSubscribe: " + s);

                    }

                    @Override
                    public void onNext(UploadFileDto dto) {
                        if (EmptyUtils.isNotEmpty(dto) && EmptyUtils.isNotEmpty(dto.getVisit_app_file_upload_response())) {
                            Boolean result = dto.getVisit_app_file_upload_response().isData();
                            if (result) {
                                successSize++;
                                Log.e(TAG, "----successSize: " + successSize);
                                Log.e(TAG, "----allSize: " + allSize);
                                progressBar.setProgress(successSize);
                                tvProgress.setText(successSize + "/" + allSize);
                                //上传成功一次
                                new Thread() {
                                    @Override
                                    public void run() {
                                        super.run();
                                        String path = file.getPath();

                                        for (int i = 0; i < upLoadFileVoList.size(); i++) {
                                            for (int j = 0; j < upLoadFileVoList.get(i).getUploadFiles().size(); j++) {
                                                if (upLoadFileVoList.get(i).getUploadFiles().get(j).getPath().equals(path)) {
                                                    Log.e(TAG, "清掉之前: " + upLoadFileVoList.get(i).getUploadFiles().size());
                                                    upLoadFileVoList.get(i).getUploadFiles().remove(file);
                                                    Log.e(TAG, "run: 清掉的" + file);
                                                    Log.e(TAG, "清掉之后: " + upLoadFileVoList.get(i).getUploadFiles().size());
                                                    break;
                                                }

                                            }
                                        }

                                        File textFile = new File(file.getPath().substring(0, file.getPath().length() - 4) + ".txt");
                                        FileUtil.deleteFile(textFile);
                                        FileUtil.deleteFile(file);
                                        Log.e(TAG, "run: " + file);
                                        Log.e(TAG, "run: " + textFile);
                                        Log.e(TAG, "run: " + path);
                                        System.gc();

                                    }
                                }.start();

                                if (successSize == allSize) {
                                    ToastUtils.showToast("上传完成，正在更新案件状态");
                                    uploadVisitRecord(Long.parseLong(applyId), session);
                                } else {
                                    initToUpload(session);
                                }


                            } else {
                                btnOk.setEnabled(true);
                                btnOk.setBackgroundResource(R.drawable.shape_button_select_bg);
                                getLoadingDialog().dismiss();
                                ToastUtils.showToast("上传失败" + result);
                            }

                        } else {
                            btnOk.setEnabled(true);
                            btnOk.setBackgroundResource(R.drawable.shape_button_select_bg);
                            getLoadingDialog().dismiss();
                            Log.e(TAG, "onNext: -----------");
                            if (EmptyUtils.isNotEmpty(dto.getError_response())) {
                                ToastUtils.showToast(dto.getError_response().getMsg() + "-" + dto.getError_response().getSub_code());
                            } else {
                                ToastUtils.showToast("上传失败");
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable t) {
                        getLoadingDialog().dismiss();
                        ApiException exception = ExceptionEngine.handleException(t);
                        ToastUtils.showToast(exception.getCode() + "-" + exception.getMsg());
                        btnOk.setEnabled(true);
                        btnOk.setBackgroundResource(R.drawable.shape_button_select_bg);
                        getLoadingDialog().dismiss();

                    }

                    @Override
                    public void onComplete() {
                        Log.e(TAG, "onComplete: ");
                    }
                });

    }

    /**
     * 删除文件
     *
     * @param visitUserDtoList
     */
    private void deletedFile(List<VisitUserDto> visitUserDtoList) {
        for (int i = 0; i < visitUserDtoList.size(); i++) {
            FileUtil.deleteFile(visitUserDtoList.get(i).getFilePath());
            FileUtil.deleteFile(visitUserDtoList.get(i).getTxtFilePath());
        }
    }

    private MediaPlayer mediaPlayer;
    private VisitUserDto currentVisitUserDto;

    @Override
    public void clickFile(final VisitUserDto visitUserDto) {
        //文件类型，1 录音，2, 拍照
        if ("1".equals(visitUserDto.getFileType())) {
            RxPermissions.getInstance(this).request(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE//写权限
            ).subscribe(new PermissionsObserver() {
                @Override
                protected void onGetPermissionsSuccess() {
                    //第一次点击
                    if (!EmptyUtils.isNotEmpty(currentVisitUserDto)) {
                        try {
                            initPlayer(visitUserDto);
                            mediaPlayer.start();
                            resetData(visitUserDto, true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (visitUserDto == currentVisitUserDto) {
                            if (mediaPlayer.isPlaying()) {
                                mediaPlayer.reset();
                                resetData(visitUserDto, false);
                            } else {
                                initPlayer(visitUserDto);
                                mediaPlayer.start();
                                resetData(visitUserDto, true);
                            }
                        } else {
                            mediaPlayer.reset();
                            try {
                                initPlayer(visitUserDto);
                                mediaPlayer.start();
                                resetData(visitUserDto, true);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }
                    currentVisitUserDto = visitUserDto;
                }

                @Override
                protected void onGetPermissionsSuccessFailuer() {
                    DialogUtils.showPerMissionDailog(Constant.FINALVALUE.EXTERNAL_MESSAGE, UploadSingleUserActivity.this);
                }
            });
        } else if ("2".equals(visitUserDto.getFileType())) {
            Intent intent = new Intent(this, ViewPhotosActivity.class);
            startActivity(intent);
            EventBus.getDefault().postSticky(visitUserDto);

        }
    }

    /**
     * 重置列表的视图状态
     *
     * @param visitUserDto
     */
    private void resetData(VisitUserDto visitUserDto, boolean play) {
        try {
            if (play) {
                for (int i = 0; i < recordList.size(); i++) {
                    if (visitUserDto == recordList.get(i)) {
                        recordList.get(i).setPlaying(true);
                    } else {
                        recordList.get(i).setPlaying(false);
                    }

                }
            } else {
                recordList.get(recordList.indexOf(visitUserDto)).setPlaying(false);

            }
            recordAdapter.notifyDataSetChanged();
        } catch (Exception e) {
        }


    }

    /**
     * 初始化 音乐
     *
     * @param visitUserDto
     */
    private void initPlayer(final VisitUserDto visitUserDto) {
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(visitUserDto.getFilePath());
            mediaPlayer.setLooping(false);//设置为循环播放
            mediaPlayer.prepare();//初始化播放器MediaPlayer
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    resetData(visitUserDto, false);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取 session
     *
     * @param userDto
     * @return
     */
    private void initLoginSession(UserDto userDto) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                LoginCollectionVo loginCollectionVo = new LoginCollectionVo();
                loginCollectionVo.setAccount(userDto.getUsername());
                loginCollectionVo.setPassword(userDto.getPassword());
                loginCollectionVo.setMerchantId(Constant.Server.merchantId);
                loginCollectionVo.setPlatform(Constant.Server.platform);

                String loginCollectionJson = JSON.toJSON(loginCollectionVo).toString();
                try {
                    Log.i(TAG, "请求参数loginCollectionJson:" + loginCollectionJson);
                    //
                    Response response = HttpUtils.post(Constant.Server.ROOT_URL + "login/", loginCollectionJson);
                    Log.i(TAG, "登陆接口返回response:" + response);
                    String rtn = response.body().string();
                    Log.i(TAG, "登陆接口返回内容:" + rtn);
                    Document doc = DocumentHelper.parseText(rtn);
                    JSONObject json = new JSONObject();
                    Dom4jUtil.dom4j2Json(doc.getRootElement(), json);
                    JSONObject jsonObjectTemp = (JSONObject) json.get("data");
                    if (EmptyUtils.isNotEmpty(jsonObjectTemp)) {

                        String session = jsonObjectTemp.get("session") + "";
                        Message msg = Message.obtain();
                        msg.what = 2001;
                        msg.obj = session;
                        handler.sendMessage(msg);

                    } else {
                        String code = (String) json.get("code");
                        String msg = (String) json.get("sub_msg");
                        Message message = Message.obtain();
                        message.obj = msg + "-" + code;
                        handler.sendMessage(message);
                    }


                } catch (Exception e) {
                    Message message = Message.obtain();
                    message.obj = "客户端异常，请稍候再试" + e.getMessage();
                    handler.sendMessage(message);
                }

            }
        }.start();
    }

}

